import { takeEvery, put } from "@redux-saga/core/effects";
import axios from "axios"
import { addProductToCart, addProductToLocalCart, changeLocalProductNumber, changeServiceProductNumber, deleteProductFromCart, deleteProductFromLocalCart, loadCarts, saveCarts } from "../actions/cart.action";

function* handleAddProductToCart(action) {
    //1,向服务器发送请求，告诉服务器我们将那一个商品添加到购物车中
    const { data } = yield axios.post("http://localhost:3005/cart/add", { gid: action.payload });
    yield put(addProductToLocalCart(data))
}
// 
function* handleLoadCarts() {
    //3,向服务器端发送请求，获取购物车列表数据
    const { data } = yield axios.get("http://localhost:3005/cart")
    yield put(saveCarts(data))
}
function* handleDeleteProductFromCart(action) {
    //  5,向服务器发送请求，告诉服务器删除哪一个商品
    const { data } = yield axios.delete("http://localhost:3005/cart/delete",
        {
            params: {
                cid: action.payload.id
            }
        });
    if (data) {
        console.log(action.payload.index)
        yield put(deleteProductFromLocalCart(action.payload.index))
    }


}
function* handleChangeServiceProductNumber(action) {
    // 7,向服务器发送请求，告诉服务器我们将那一个商品数量更改了
    const { data } = yield axios.put("http://localhost:3005/cart", action.payload)
    yield put(changeLocalProductNumber(data))
}
export default function* CartSaga() {
    // 1,向服务器发送请求，告诉服务器我们将那一个商品添加到购物车中
    yield takeEvery(addProductToCart, handleAddProductToCart)
    // 3,向服务器端发送请求，获取购物车列表数据
    yield takeEvery(loadCarts, handleLoadCarts)
    // 5,向服务器发送请求，告诉服务器删除哪一个商品
    yield takeEvery(deleteProductFromCart, handleDeleteProductFromCart)
    //7,向服务器发送请求，告诉服务器我们将那一个商品数量更改了
    yield takeEvery(changeServiceProductNumber, handleChangeServiceProductNumber)
}